<template>
  <div class="userList">
    <el-card class="box-card">
      <!-- 面包屑 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 搜索与 添加 -->
      <div class="add-seek">
          <div class="seek">
          <el-input v-model="query" placeholder="请输入搜索关键字"></el-input>
            <el-button @click='seek'><i class="el-icon-search"></i></el-button>
          </div>
          <el-button type="success" plain @click="appendUser = true">添加用户</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="#">
          </el-table-column>

          <el-table-column prop="username" label="姓名">
          </el-table-column>

          <el-table-column prop="email" label="邮箱">
          </el-table-column>

          <el-table-column prop="mobile" label="电话">
          </el-table-column>
          <!-- 状态 -->
          <el-table-column label="用户状态">
              <template v-slot:default='obj'>
                  <el-switch
                  @change="changeState(obj.row.id,obj.row.mg_state)"
                  v-model="obj.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949" >
                </el-switch>
              </template>
          </el-table-column>
          <!-- 操作 -->
          <el-table-column prop="ope" label="操作">
              <template v-slot:default='obj'>
                <el-button @click="btnAmend(obj.row)"  plain size="small" type="primary" icon="el-icon-edit" ></el-button>
                <el-button @click='deleteData(obj.row.id)'  plain size="small" type="danger"  icon="el-icon-delete"></el-button>
                <el-button @click="allRole(obj.row)" plain size="small" type="success" icon="el-icon-check">分配角色</el-button>
              </template>
          </el-table-column>
      </el-table>
      <!-- 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagenum"
          :page-sizes="[2, 4, 6, 8]"
          :page-size='pagesize'
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

    </el-card>

       <!-- 修改数据 -->
       <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
          <el-form :model="form" :rules="rules" ref="form" status-icon>
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-tag type="info">{{form.username}}</el-tag>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
              <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
              <el-input v-model="form.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="amendSure">确 定</el-button>
          </div>
       </el-dialog>

       <!--添加用户 -->
       <el-dialog title="添加用户" :visible.sync="appendUser" @close='close'>
          <el-form :model="addFrom" :rules="rules" ref="addFrom" status-icon>
            <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
              <el-input v-model="addFrom.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
              <el-input type="password" v-model="addFrom.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
              <el-input v-model="addFrom.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
              <el-input v-model="addFrom.mobile" placeholder="请输入手机号"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="appendUser = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </div>
       </el-dialog>

        <!-- 角色分配 -->
        <el-dialog title="角色分配" :visible.sync="soleUser">
          <el-form :model="roleFrom" :rules="rules" ref="roleFrom" status-icon>
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-tag type="info">{{roleFrom.username}}</el-tag>
            </el-form-item>

            <el-form-item label="角色列表" :label-width="formLabelWidth">
              <el-select v-model="roleFrom.rid" placeholder="请选择角色" >
                <el-option :label="itme.roleName" :value="itme.id" v-for='itme in roleList' :key="itme.id"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="soleUser = false">取 消</el-button>
            <el-button type="primary" @click="btnRole">分 配</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>

export default {
  data () {
    return {
      query: '',
      pagenum: 1,
      pagesize: 2,
      tableData: [],
      // 总页数
      total: 0,
      dialogFormVisible: false,
      appendUser: false,
      soleUser: false,
      // 修改数据
      form: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      // 添加
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 角色分配
      roleFrom: {
        username: '',
        id: '',
        rid: ''
      },
      // 所有角色
      roleList: [],
      formLabelWidth: '120px',
      // 表单校验
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '亲输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      // ajax 请求 获取 用户列表数据
      const { meta, data } = await this.$axios.get('users', {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      })
      if (meta.status === 200) {
        // 成功, 应该将 users / total 存起来, 用于表格的渲染
        this.tableData = data.users
        this.total = data.total
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 提示信息
    hintMessage (meta, code = 200) {
      if (meta.status === code) {
        this.$message({
          message: meta.msg,
          type: 'success',
          duration: '1000'
        })
      } else {
        this.$message({
          message: meta.msg,
          type: 'error',
          duration: '1000'
        })
      }
    },
    // 条数发生改变时触发
    handleSizeChange (value) {
      this.pagesize = value
      this.getUserList()
    },
    // 页数发生改变时触发
    handleCurrentChange (value) {
      // console.log(value)
      this.pagenum = value
      this.getUserList()
    },
    // 搜索
    seek () {
      // console.log(this.query)
      this.pagenum = 1
      this.getUserList()
    },
    // 状态
    async changeState (id, flag) {
      // console.log(id, flag)
      // 发送 ajax
      try {
        const { meta } = await this.$axios.put(`users/${id}/state/${flag}`)
        this.hintMessage(meta)
      } catch (err) {
        console.log(err)
      }
    },
    // 修改数据
    btnAmend ({ id, username, mobile, email }) {
      this.dialogFormVisible = true
      this.form.id = id
      this.form.username = username
      this.form.mobile = mobile
      this.form.email = email
    },
    async amendSure () {
      try {
        this.dialogFormVisible = false
        //  await : 等待
        await this.$refs.form.validate()
        // 但执行到这里说明校验成功
        const { id, email, mobile } = this.form
        const { meta } = await this.$axios.put(`users/${id}`, { email, mobile })
        // 提示信息
        this.hintMessage(meta)
        this.getUserList()
      } catch (err) {
        console.log(err)
      }
    },
    // 删除数据
    async deleteData (id) {
      // console.log(id)
      try {
        await this.$confirm('确定要删除这位用户吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 执行到这里说敏点击来确认
        const { meta } = await this.$axios.delete(`users/${id}`)
        // 提示信息
        this.hintMessage(meta)
        // 点击删除因当还在当前页面显示不用跳到第一页  只有当 当前页面的数据只有一条时点击删除
        // 当前页数减一
        if (this.tableData.length === 1 && this.pagenum > 1) {
          this.pagenum--
        }
        this.getUserList()
      } catch (err) {
        console.log(err)
      }
    },
    // 添加用户
    async addUser () {
      try {
        await this.$refs.addFrom.validate()
        this.appendUser = false
        // 当执行到这一步说名校验成功
        const { username, password, email, mobile } = this.addFrom
        const { meta } = await this.$axios.post('users', { username, password, email, mobile })
        this.hintMessage(meta, 201)
        this.pagenum = Math.ceil(++this.total / this.pagesize)
        this.getUserList()
      } catch (err) {
        console.log(err)
      }
    },
    // 关闭添加对话框时重置表单数据
    close () {
      // console.log(this.$refs)
      // 重置表单
      this.$refs.addFrom.resetFields()
    },
    // 分配角色
    async allRole (row) {
      // console.log(row)
      this.soleUser = true
      try {
        const res = await this.$axios.get('roles')
        this.roleList = res.data
        this.roleFrom.username = row.username
        this.roleFrom.id = row.id
        // 根据 id 发送 ajax 获取 当前用户的信息 从而获取 rid
        const { data } = await this.$axios.get(`users/${row.id}`)
        // 如果 rid 等于 -1 说明 当前的用户还没有 设置角色
        this.roleFrom.rid = data.rid === -1 ? '' : data.rid
      } catch (err) {
        console.log(err)
      }
    },
    async btnRole () {
      this.soleUser = false
      try {
        const { id, rid } = this.roleFrom
        const { meta } = await this.$axios.put(`users/${id}/role`, { rid })
        // 消息提示
        this.hintMessage(meta)
        this.getUserList()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
   .userList {
    .el-breadcrumb{
       height: 40px;
       line-height: 40px;
       border-bottom: 1px solid #cccccc;
       margin-bottom: 10px;
    }
    .add-seek{
      display: flex;
      margin-bottom: 15px;
      .seek{
        display: flex;
        margin-right: 20px;
        .el-button{
          border-left: none;
          border-radius: 0 4px 4px 0;
          border-color: #cccccc;
          background-color: #ffffff;
          color: inherit;
        }
      }
    }
    .el-pagination{
      margin-top: 15px;
    }
   }
</style>
